<template>
  <div>
    <el-form
      ref="form"
      :model="form"
      label-width="120px"
      style="width: 650px"
      prop="school_name"
      :rules="rules"
    >
      <el-form-item label="驾校名称" prop="school_name">
        <el-input type="text" v-model="form.school_name"></el-input>
      </el-form-item>
      <el-form-item label="驾校照片" prop="school_cover">
        <el-upload
          class="avatar-uploader"
          :action="`${UPLOADURL}/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :limit="1"
        >
          <img
            v-if="form.school_cover"
            :src="form.school_cover"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="选择位置">
        <div id="main" style="height: 200px; border: 1px solid #666"></div>
      </el-form-item>
      <el-form-item label="详细地址" prop="school_address">
        <el-input type="text" v-model="form.school_address"></el-input>
      </el-form-item>
      <el-form-item label="省份" prop="schoolprovince">
        <el-input type="text" v-model="form.schoolprovince"></el-input>
      </el-form-item>
      <el-form-item label="城市" prop="schoolcity">
        <el-input type="text" v-model="form.schoolcity"></el-input>
      </el-form-item>
      <el-form-item label="地区" prop="schooldistrict">
        <el-input type="text" v-model="form.schooldistrict"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="school_phone">
        <el-input type="text" v-model="form.school_phone"></el-input>
      </el-form-item>
      <el-form-item label="教授驾照类型" prop="licensetype">
        <el-checkbox-group v-model="form.licensetype">
          <el-checkbox
            v-for="item in licensetypes"
            :key="item.license_type_id"
            :label="item.license_type"
            :value="item.license_type"
          ></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 驾校标签 -->
      <el-form-item label="驾校标签" prop="schoollabel">
        <el-select
          v-model="form.schoollabel"
          multiple
          placeholder="请选择教练标签"
        >
          <el-option
            v-for="item in school_labels"
            :key="item.school_label_id"
            :label="item.school_label"
            :value="item.school_label"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addshool">新增驾校</el-button>
        <el-button @click="resetform">重置</el-button>
        <el-button @click="cancel">取消返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import httpApi from "@/http";
export default {
  data() {
    return {
      form: {
        school_name: "",
        licensetype: [],
        school_phone: "",
        school_score: "",
        school_address: "",
        schoollabel: [],
        schoolcity: "",
        schoolprovince: "",
        schooldistrict: "",
        school_cover: "",
        school_lat: "",
        school_lng: "",
      },
      // 驾校标签
      school_labels: [],
      licensetypes: [],

      rules: {
        school_cover: {
          required: true,
          message: "请上传驾校图片",
          trigger: "blur",
        },
        school_name: {
          required: true,
          message: "请输入驾校名称",
          trigger: "blur",
        },
        school_phone: {
          required: true,
          message: "请输入手机号码",
          trigger: "blur",
        },
        school_score: {
          required: true,
          message: "请输入0-5的评分",
          trigger: "blur",
        },
        school_address: {
          required: true,
          message: "请输入详细地址",
          trigger: "blur",
        },
        schoolcity: {
          required: true,
          message: "请输入城市",
          trigger: "blur",
        },
        schoolprovince: {
          required: true,
          message: "请选择省份城市",
          trigger: "blur",
        },
        schooldistrict: {
          required: true,
          message: "请选择地区城市",
          trigger: "blur",
        },
      },
    };
  },
  methods: {
    resetform() {
      this.form.school_name = "";
      this.form.licensetype = [];
      this.form.school_phone = "";
      this.form.school_score = "";
      this.form.school_address = "";
      this.form.schoollabel = "";
      this.form.schoolcity = "";
      this.form.schoolprovince = "";
      this.form.schooldistrict = "";
      this.form.school_cover = "";
      this.form.school_lat = "";
      this.form.school_lng = "";
    },
    cancel() {
      this.$router.push("/home/driverschool-list");
    },
    addshool() {
      this.form.licensetype = this.form.licensetype.join("/");
      this.form.schoollabel = this.form.schoollabel.join("/");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          httpApi.schoolApi.add(this.form).then((res) => {
            console.log("驾校添加", res);
            if (res.data.code == 200) {
              this.$message.success("驾校添加成功");
              this.$router.push("/home/driverschool-list");
            } else {
              this.$message.error("添加失败请检查");
              this.form.licensetype = this.form.licensetype.split("/");
              this.form.schoollabel = this.form.schoollabel.split("/");
            }
          });
        }
      });
    },
    // 图片上传处理
    handleAvatarSuccess(res, file) {
      console.log(res, file);
      this.form.school_cover = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传驾校照片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传驾校照片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 初始化地图
    initMap() {
      AMapLoader.load({
        key: "df55e080940cae4c6de2986c20b50879", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("main", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [106.550483, 29.563707], //初始化地图中心点位置
          });
          // 为地图对象绑定点击事件
          this.map.on("click", (e) => {
            let lng = e.lnglat.getLng();
            let lat = e.lnglat.getLat();
            console.log(`经纬度：[${lng},${lat}]`);
            // 调用高德地图的web服务接口，查询当前经纬度的坐标
            let geocoder = new AMap.Geocoder();
            geocoder.getAddress([lng, lat], (status, result) => {
              console.log(status, result);
              let info = result.regeocode.addressComponent;
              this.form.school_address = result.regeocode.formattedAddress;
              if (info.city != "") {
                this.form.schoolcity = info.city;
              } else {
                this.form.schoolcity = info.province;
              }
              // this.form.schoolcity = info.city;
              this.form.schooldistrict = info.district;
              this.form.schoolprovince = info.province;
              this.form.school_lat = lat;
              this.form.school_lng = lng;
            });
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    inf1school() {
      httpApi.schoolApi.querytype().then((res) => {
        console.log("加载驾校标签", res);
        this.school_labels = res.data?.data?.result;
      });
    },
    infolicensetype() {
      httpApi.commpleApi.queryLicensetype().then((res) => {
        console.log("驾照类型标签", res);
        this.licensetypes = res.data?.data?.result;
      });
    },
    infocity() {
      httpApi.commpleApi.queryallCity().then((res) => {
        console.log("加载城市标签", res);
      });
    },
  },
  mounted() {
    this.initMap();
    this.infocity();
    this.inf1school();
    this.infolicensetype();
  },
};
</script>

<style lang="scss" scoped></style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>
